const formatTime = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}

const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : '0' + n
}

const checkLogin = () => {
    var user = wx.getStorageSync('user') || {};
    if (user.hasOwnProperty('id')) {
        return true;
    }
    return false;
};

const api_gateway = "https://mc.cqbes.com/api/webapp/";

const api = {
    get: function (url, params, callback) {
        var tokens = wx.getStorageSync('tokens') || {};
        console.log(tokens);

        var header = {};
        if (tokens.hasOwnProperty('access_token')) {
            header['Authorization'] = tokens.token_type + ' ' + tokens.access_token;
        }

        wx.request({
            url: api_gateway + url,
            data: params,
            header: header,
            method: 'GET',
            dataType: 'json',
            success: function(res) {
                callback(res.data)
            },
            fail: function(res) {
                callback({
                    status: false,
                    msg: '网络请求失败',
                    data: []
                })
            },
        });
    },

    post: function (url, params, callback) {
        var tokens = wx.getStorageSync('tokens') || {};
        console.log(tokens);

        var header = {};
        if (tokens.hasOwnProperty('access_token')) {
            header['Authorization'] = tokens.token_type + ' ' + tokens.access_token;
        }

        wx.request({
            url: api_gateway + url,
            data: params,
            header: header,
            method: 'POST',
            dataType: 'json',
            success: function (res) {
                callback(res.data)
            },
            fail: function (res) {
                callback({
                    status: false,
                    msg: '网络请求失败',
                    data: []
                });
            },
        });
    }
};

module.exports = {
  formatTime: formatTime,
  api: api,
  checkLogin: checkLogin
}
